

package org.itboys.mobile.service.mysql.front;

import org.itboys.admin.dto.lasted.SundayUploadDto;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.product.SundayProductCategoryMapper;
import org.itboys.mobile.dto.SundayCommentDto;
import org.itboys.mobile.dto.product.SundayProductDto;
import org.itboys.mobile.dto.promotion.SundayTeamGroupDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.entity.mysql.promotion.SundayTeamGroup;
import org.itboys.mobile.service.mongo.front.SundayFrontCollectionService;
import org.itboys.mobile.service.mongo.front.SundayFrontCommentService;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_商品_service_mobile
 */


@Service
public class SundayFrontProductService extends BaseMySqlService<SundayProduct> {
    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayUploadService uploadService;
    @Autowired
    private SundayFrontCollectionService collectionService;
    @Autowired
    private ResourceHolder resourceHolder;


    @Autowired
    private SundayFrontCommentService commentService;

    @Autowired
    private SundayFrontTeamGroupService teamGroupService;

    @Autowired
    private SundayProductCategoryMapper productCategoryMapper;


    /**
     * 分页获取商品
     *
     * @param request
     * @param memberId
     * @param type     1商城商品。2积分商品，3采购商品
     */

    public List<SundayProductDto> selectProduct(HttpServletRequest request, Long memberId,Long shopId, Long firstCatId,Long secondCatId, Integer type,Long brandId) {

        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request, "name");
        param.put("status",SundayCommonConstants.product_status_ysj);
        param.put("storeBiggerEqual",1);//库存大于等于
        //一级分类ID
        if(LongUtil.isNotZreo(firstCatId)){
            List<Long> secondCatIds = productCategoryMapper.findByParent(firstCatId);
            param.put("categoryIds", secondCatIds);
        }
        //二级分类ID
        if (LongUtil.isNotZreo(secondCatId)) {
            param.put("categoryId", secondCatId);
        }
        //店铺的ID
        if(LongUtil.isNotZreo(shopId)){
            param.put("shopId",shopId);
        }
        //店铺的ID
        if(LongUtil.isNotZreo(brandId)){
            param.put("brandId",brandId);
        }
        if (type != null) {
            param.put("type", type);
        //只查询1普通，2新品，3特卖，商品类型
        }else{
            param.put("types",Arrays.asList(new Integer[]{
                    SundayCommonConstants.type_putong,
                    SundayCommonConstants.type_xinpin,
                    SundayCommonConstants.type_temai,
                    SundayCommonConstants.type_haitao
            }));
        }
        //
       /* for (String key : param.keySet()) {
               System.out.println("key= "+ key + " and value= " + param.get(key));
        }*/


        List<SundayProductDto> productDtos = packageDtoMuilt(super.select(param));
       /* //2018年2月3日，商品名称截取
        for(SundayProductDto productDto:productDtos){
            if(StringUtils.isNotEmpty(productDto.getName())&&
                    productDto.getName().length()>6){
                productDto.setName(productDto.getName().substring(0,7)+"...");
            }
        }*/
        return productDtos;
    }
    public List<SundayProductDto> selectProductNoPage(Map<String,Object> param) {
        List<SundayProductDto> productDtos = packageDtoMuilt(super.select(param));
        param.put("status",SundayCommonConstants.product_status_ysj);
        /*for(SundayProductDto productDto:productDtos){
            if(StringUtils.isNotEmpty(productDto.getName())&&
                    productDto.getName().length()>6){
                productDto.setName(productDto.getName().substring(0,7)+"...");
            }
        }*/
        return productDtos;
    }
    /**
     * 查询商品详情
     * @param memberId
     * @param productId
     * @return
     */
    public SundayProductDto getDetail(Long memberId,Long productId){
        SundayProduct product = super.find(productId);

        SundayProductDto dto  =packageDtoSingle(super.find(productId));
        //组装轮播图
        List<SundayUploadDto> rollImages = uploadService.selectNoPage(product.getId(),SundayProduct.class.getSimpleName());
        dto.setRollImages(rollImages);
        //商品详情URL
        String descUrl =resourceHolder.getStringValue("mobileRoot")+"/sunday/mobile/product/desc?id="+product.getId();
        dto.setDescUrl(descUrl);
        //判断受否收藏
        Integer isCollection =collectionService.checkIsCollection(memberId, SundayCommonConstants.collection_type_product,product.getId());
        dto.setIsCollection(isCollection);
        logger.info("商品是否收藏="+isCollection);
        //加载推荐商品
        Map<String,Object> param = new HashMap<>();
        param.put("sort_name","saleNumber");
        param.put("sort_order","DESC");
        param.put("row_start",0);
        param.put("row_size",4);
        param.put("categoryId",product.getCategoryId());
        param.put("type",product.getType());
        List<SundayProductDto> products = selectProductNoPage(param);
        for(SundayProductDto productDto:products){
            if(org.apache.commons.lang.StringUtils.isNotEmpty(productDto.getName())&&
                    productDto.getName().length()>6){
                productDto.setName(productDto.getName().substring(0,6)+"...");
            }
        }
        dto.setProducts(products);




        //加载评论
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("outClassName",SundayProduct.class.getSimpleName());
        param.put("outClassId",product.getId());
        //评论总数
        Long commentCount = commentService.count(param);
        dto.setCommentCount(commentCount);
        //默认加载3条评论
        List<SundayCommentDto> comments = commentService.getCommentByNumber(productId,3);
        dto.setComments(comments);

        //商品库存不足，自动下架
        if(product.getStore()<=0){
            // status=SundayCommonConstants.product_status_yxj;
            product.setStatus(SundayCommonConstants.product_status_yxj);
            super.update(product);
            dto.setStatus(SundayCommonConstants.product_status_yxj);

        }
        //根据商品属性判断对应具体的属性
        //2018年1月10日，检查商品类型
        //4，海淘商品
        if(product.getType()==SundayCommonConstants.type_haitao){
            dto.setTax(product.getTax());
            dto.setTaxMsg(product.getTaxMsg());
        //6，金领商品
        }else if(product.getType()== SundayCommonConstants.type_fenxiao){
        //5，爱购币商品
        }else if(product.getType()==SundayCommonConstants.type_aigou){
            dto.setAigouPrice(product.getAigouPrice());
        //8.秒杀商品，根据时间判断商品状态
        }else if(product.getType()==SundayCommonConstants.type_miaosha){
            //根据时间
            if (product.getStatus() == SundayCommonConstants.product_status_ysj) {
                Integer  secKillHour = Integer.valueOf(product.getSecKillTimeGroupValue());
                  Calendar calendar=  Calendar.getInstance();
                Integer nowHour =calendar.get(Calendar.HOUR_OF_DAY);
                //秒杀商品未开始或已结束
                    if(nowHour>secKillHour){
                        dto.setStatus(SundayCommonConstants.product_status_yjs);
                    }
                    if(nowHour<secKillHour){
                        dto.setStatus(SundayCommonConstants.product_status_wks);
                    }
                    //2018年1月25日，商品详情中设置秒杀商品截至时间
                   if(nowHour==secKillHour){
                        calendar.set(Calendar.HOUR_OF_DAY,Integer.valueOf(product.getSecKillTimeGroupValue()));
                        calendar.set(Calendar.MINUTE,59);
                        calendar.set(Calendar.SECOND,59);
                        dto.setSecKillTime(TimeUtils.formatToTime(calendar.getTime()));
                   }

            }
            dto.setSecKillTimeGroupValue(product.getSecKillTimeGroupValue());
        //9.拼团商品
        }else if(product.getType()==SundayCommonConstants.type_pintuan){
            dto.setTeamPrice(product.getTeamPrice());
            //商品对应的拼团组。商品详情显示全部拼团组。
            List<SundayTeamGroupDto> teamGroupDtos =teamGroupService.getGroup(null,product.getId(),null);
            dto.setTeamGroups(teamGroupDtos);
            dto.setTeamGroupNumber(teamGroupDtos.size());

        }
        //装载商户

        //判断商品商家
        if(LongUtil.isNotZreo(product.getShopId())){
            SundayMember business = memberService.getById(product.getShopId());
            dto.setShopId(product.getShopId());
            dto.setShopName(business.getNickName());
            dto.setShopImage(resourceHolder.getStringValue("imgRoot")+business.getImage());
            dto.setShopDesc(business.getDesc());
        }else{
            dto.setShopId(0l);
            dto.setShopName("爱购梵品");
            dto.setShopImage("/1.jpg");
        }

        //分享信息
        dto.setShareUrl(resourceHolder.getStringValue("weixinRoot")+"/sunday/weixin/product/detail?id="+product.getId());
        dto.setShareImage(dto.getImage());
        dto.setShareTitle("[爱购梵品]"+product.getName());
        dto.setShareDesc("我发现一个不错的商品,快点击查看吧");

        //获取购物车商品数量
      //  Integer cartProductNum = cartService.getCartProductNum(memberId);
       // dto.setCartProductNum(cartProductNum);
        return dto;

    }

    /**
     * 获取收藏/店铺（分销）商品
     * @param request
     * @param memberId
     */
    public List<SundayProductDto> getCollection(HttpServletRequest request,Long memberId,Integer type){
        List<Long> productIds = collectionService.selectCollection(memberId,type);
        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request, "name");
        List<SundayProduct> products = new ArrayList<>();
        if(ListUtil.isNotNull(productIds)){
            param.put("ids",productIds);
            products=super.select(param);
        }
        return packageDtoMuilt(products);

    }


    /**
     * 组装DTO
     * @param product
     * @return
     */
    public SundayProductDto packageDtoSingle(SundayProduct product){
        String imageRoot = resourceHolder.getStringValue("imgRoot");
        SundayProductDto dto = new SundayProductDto(
        product.getId(),product.getCreateTime(),product.getCreateDate(),
               product.getName(),product.getTitle(),product.getStandard(),product.getCategoryId(),product.getCategoryName(),product.getBrandId(),
               product.getBrandName(),product.getMarketPrice(),product.getPrice(),product.getSaleNumber(),
               product.getStore(),product.getStatus(),product.getType(),product.getBarCode(),product.getStar(),product.getPlace(),product.getDesc(),product.getIsDiscount()
       );
       dto.setImage(imageRoot+product.getImage());
        return dto;
    }
    /**
     * 组装DTO
     * @param products
     * @return
     */
    public List<SundayProductDto> packageDtoMuilt(List<SundayProduct> products){

        List<SundayProductDto> dtos = new ArrayList<SundayProductDto>();
        Map<String,Object> param = new HashMap<>();
        List<Long> shopIds = new ArrayList<>();
        List<Long> teamProductIds = new ArrayList<>();
        for(SundayProduct product:products){
            if(LongUtil.isNotZreo(product.getShopId())){
                shopIds.add(product.getShopId());
            }
           if(product.getType()==SundayCommonConstants.type_pintuan){
               teamProductIds.add(product.getId());
           }
        }
        String imageRoot = resourceHolder.getStringValue("imgRoot");
        List<SundayMember> shops=new ArrayList<>();
        if(ListUtil.isNotNull(shopIds)){
            param.clear();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("userType",SundayCommonConstants.user_type_business);
            param.put("id in",shopIds);
            shops=memberService.list(param);
        }
        //查询商品的拼团组
        List<SundayTeamGroup> teamGroups = new ArrayList<>();
        if(ListUtil.isNotNull(teamProductIds)){
            param.clear();
            param.put("productIds",teamProductIds);
            param.put("status",SundayCommonConstants.team_status_ptz);
            teamGroups=teamGroupService.select(param);
        }
        for(SundayProduct product:products){
            //根据商品类型执行一些判断，列表状态下只需要判断以下类型
            //秒杀，拼团
           SundayProductDto dto = packageDtoSingle(product);
          //4，海淘商品
           if(product.getType()==SundayCommonConstants.type_haitao){
               dto.setTax(product.getTax());
               dto.setTaxMsg(product.getTaxMsg());
          //6，秒杀
           } else if(product.getType()==SundayCommonConstants.type_miaosha){
             if (product.getStatus() == SundayCommonConstants.product_status_ysj) {
                Integer  secKillHour = Integer.valueOf(product.getSecKillTimeGroupValue());
                Integer nowHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                //秒杀商品未开始或已结束
                if(nowHour>secKillHour){
                    dto.setStatus(SundayCommonConstants.product_status_yjs);
                }
                if(nowHour<secKillHour){
                    dto.setStatus(SundayCommonConstants.product_status_wks);
                }
             }
                 dto.setSecKillTimeGroupValue(product.getSecKillTimeGroupValue());
            //拼团
            }else if(product.getType()==SundayCommonConstants.type_pintuan){

                dto.setTeamMax(product.getTeamMemberNum());
                //平团商品在列表页，显示拼团价格
               dto.setPrice(product.getTeamPrice());
               //teamPrice,临时用一下，结算中使用
               dto.setTeamPrice(product.getPrice());
               //获取商品正在拼团的人数
               int teamGroupNumber=0;
                if(ListUtil.isNotNull(teamGroups)){

                    for(SundayTeamGroup teamGroup:teamGroups){
                        if(LongUtil.isNotZreo(teamGroup.getProductId())&&
                                product.getId().longValue()==teamGroup.getProductId().longValue()){
                            teamGroupNumber++;
                        }
                    }

                }
               dto.setTeamGroupNumber(teamGroupNumber);
            }/*else if(product.getType()==SundayCommonConstants.type_xinpin){//top10
               SundayProductBrand productBrand = productBrandService.find(product.getBrandId());
               dto.setBrandImage(imageRoot+productBrand.getImage());
           }else if(product.getType()==SundayCommonConstants.type_aigou){
               dto.setAigouPrice(product.getAigouPrice());
           }*/

            if(LongUtil.isNotZreo(product.getShopId())){
                 for(SundayMember shop:shops){
                     if(shop.getId()==product.getShopId().longValue()){
                         dto.setShopId(shop.getId());
                         dto.setShopName(shop.getNickName());
                         dto.setShopImage(imageRoot+shop.getImage());
                         dto.setShopDesc(shop.getDesc());
                        break;
                     }
                 }
            }else{
                dto.setShopId(0l);
                dto.setShopName("爱购梵品");
                dto.setShopImage(imageRoot+"/1.jpg");
            }
            //匹配门店信息
                dtos.add(dto);
        }

        return dtos;
        }
    }



